import React, { useEffect, useRef, useState } from "react";
import {
  NavBar,
  Swiper,
  Image,
  Card,
  Button,
  Popup,
  ImageViewer,
  Stepper,
  Badge,
  Toast,
  Modal,
  Input,
  Form,
  Switch,
  TextArea,
  List,
} from "antd-mobile"; // 组件
import { useLocation, useNavigate, useSelector, useDispatch } from "umi"; // 路由
import { setCart } from "@/utils/index"; // 购物车商品数量存缓存 做redux持久化
import { addOrder, addShoppingCartApi, getCommentApi } from "@/api"; // 接口
import Qs from "qs";
import Icon from "../../components/icon/index";
import "./assets/style.scss";
import axios from "axios";

interface userType {
  id: number;
  name: string;
  nickname: string;
  password: string;
  email: string;
  address: string;
  avatar: string;
  age: number;
}

export default function index() {
  const location = useLocation();
  const navigate = useNavigate();
  const iphone = useRef<any>(null);
  const id = location.state.id; // 商品分类页 跳转 携带的商品id
  /* 头部返回ProductPage页 */
  const backProductPage = () => {
    navigate("/cate", { state: { id: location.state.categoryId } });
  };
  // 存储商品的评论

  /* 渲染商品详情 */
  const [cateContent, setCateContent] = useState<any>(); // 单个商品 详细信息
  const [productDesc, setProductDesc] = useState<any>([]);
  const [list, setList] = useState<any>([]); //获取商品的评论
  const [user, setUser] = useState<userType>();
  const featchContent = (): void => {
    axios({
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        token: localStorage.getItem("token"),
      },
      method: "get",
      url: `http://43.139.124.13:8888/product/getById/${id}`,
      data: Qs.stringify({ id }),
    }).then((res: any) => {
      console.log(res);
      setList(res.data.data.commentList);
      setCateContent(res.data.data);
      setImages([res.data.data.image]);
      productDesc.push(res.data.data);
    });
  };
  /* 底部购物车 点击 */
  const [visible, setVisible] = useState(false); // 购物车弹出层 绑定数据
  const [buy, setBuy] = useState(false); // 立即购买弹出层 绑定数据
  const [buyForm, setBuyForm] = useState(false);
  const cartClick = () => {
    setVisible(true);
  };
  const buyClick = () => {
    setBuy(true);
  };
  /* 图片预览 */
  const [images, setImages] = useState<any>([]);
  const [imageShow, setImageShow] = useState(false);

  const [stepperValue, setStepperValue] = useState<Number>(1); // 存储步进器 数据
  const stepperClick = (stpValue: Number): void => {
    setStepperValue(stpValue); // 修改步进器数据
  };
  const buttonCart = async () => {
    // 点击加入购物车
    const res = await addShoppingCartApi([
      {
        count: stepperValue,
        productId: id,
      },
    ]);
    if (res.data.code == "200") {
      Toast.show({
        content: "添加成功",
        afterClose: () => {
          featchContent();
        },
      });
    }
    setBuyForm(true);
    console.log(res);
  };

  /* 收藏功能 */
  const collect = async (id: number) => {
    const res = await axios({
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        token: localStorage.getItem("token"),
      },
      method: "get",
      url: `http://43.139.124.13:8888/collect/addCollectProduct`,
      params: { productId: id },
    });
    if (res.data.code == "200") {
      Toast.show({
        content: res.data.msg,
      });
    } else {
      Toast.show({
        content: res.data.msg,
      });
    }
  };

  /* 点赞功能 */
  const addProductStar = async (id: number) => {
    const res = await axios({
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        token: localStorage.getItem("token"),
      },
      method: "get",
      url: "http://43.139.124.13:8888/star/addProductStar",
      params: { productId: id },
    });
    console.log(res);

    if (res.data.code == "200") {
      Toast.show({
        content: "点赞成功",
      });
    } else {
      Toast.show({
        content: res.data.msg,
      });
    }
  };
  /* 评论功能 */
  /**
   * @param value 传入用户id，商品id和评论内容即可
   */
  const onFinish = async (value: any) => {
    const res = await getCommentApi({
      ...value,
      userId: localStorage.getItem("userId"),
      productId: id,
    });
    if (res.data.code == "200") {
      Toast.show({
        content: res.data.msg,
      });
      navigate(0);
    }
  };
  const comment = () => {
    Modal.show({
      content: (
        <>
          <Form
            onFinish={onFinish}
            footer={
              <Button block type="submit" color="primary" size="large">
                提交
              </Button>
            }
            layout="horizontal"
          >
            <Form.Header>评论该商品</Form.Header>
            <Form.Item name="context" label="评论">
              <TextArea
                placeholder="请输入评论内容"
                maxLength={100}
                rows={2}
                showCount
              />
            </Form.Item>
          </Form>
        </>
      ),
      closeOnMaskClick: true,
      // actions: [],
    });
  };
  // 下单功能
  const [paypay, setPaypay] = useState<any>();
  // 获取用户信息并且获取用户地址
  const getUserInfo = async () => {
    const res = await axios({
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        token: localStorage.getItem("token"),
      },
      method: "get",
      url: `http://43.139.124.13:8888/user/${localStorage.getItem("userId")}`,
    });
    setUser(res.data.data);
    console.log(res);
  };
  const addOrders = async () => {
    const { value } = iphone.current?.nativeElement;
    const res = await addOrder({
      cartDTOList: [
        {
          count: stepperValue,
          productId: id,
        },
      ],
      linkAddress: user?.address,
      linkPhone: value,
    });
    setPaypay(res.data);
    localStorage.setItem("pay", res.data);
    setTimeout(() => {
      const div = document.createElement("div");
      div.innerHTML = res.data; //后台返回接收到的html数据
      document.body.appendChild(div);
      document.forms[0].submit();
    }, 1000);
    // console.log(res);
  };

  /* useEffect 钩子 */
  useEffect(() => {
    featchContent();
    getUserInfo();
  }, []);

  return (
    <div className="contentBox">
      {/* 头部 */}
      <NavBar back="返回" onBack={backProductPage}>
        商品详情
      </NavBar>

      <div className="titleBox">
        {/* 走马灯部分 */}
        {/* 让轮播图下来没有实际作用 */}
        <div style={{ width: "100%", height: 40 }}></div>
        <Swiper autoplay loop>
          {productDesc?.map((element: any) => (
            <Swiper.Item key={element.id}>
              <Image
                src={element.image}
                style={{ width: "100%", height: "200PX" }}
                onClick={() => {
                  setImageShow(true);
                }}
              />
            </Swiper.Item>
          ))}
        </Swiper>
        {/* 商品 card */}
        <div className="cateList">
          <Card key={cateContent?.id}>
            <div className="cardLeft">
              <Image style={{ width: 150 }} src={cateContent?.image} />
            </div>
            <div className="cardRight">
              <div className="price">
                <span>
                  {cateContent?.name ? cateContent?.name : "暂无详情"}
                </span>
                <span
                  style={{ color: "red" }}
                >{`￥${cateContent?.price}`}</span>
              </div>
            </div>
          </Card>
        </div>
        {/* 评论区域 */}
        <List header="评论区">
          {list.map(
            (item: {
              id: React.Key | null | undefined;
              context:
                | string
                | number
                | boolean
                | React.ReactElement<
                    any,
                    string | React.JSXElementConstructor<any>
                  >
                | React.ReactFragment
                | React.ReactPortal
                | null
                | undefined;
            }) => (
              <List.Item key={item.id}>{item.context}</List.Item>
            )
          )}

          <div style={{ height: 50 }}></div>
        </List>
      </div>
      {/* 底部加入购物车 */}
      <div className="cartBox">
        <div>
          <Icon
            onClick={() => {
              addProductStar(id);
            }}
            name="dianzan"
            color="red"
            size={20}
          />
          点赞
        </div>
        <div>
          <Icon
            onClick={() => {
              collect(id);
            }}
            name="shoucang"
            size={20}
          />
          收藏
        </div>
        <div
          onClick={() => {
            comment();
          }}
        >
          <Icon name="pinglun" size={20} />
          评论
        </div>
        <Button color="warning" onClick={cartClick}>
          加入购物车
        </Button>
        <Button color="danger" onClick={buyClick}>
          立即购买
        </Button>
      </div>
      {/* 购物车弹出层 */}
      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        bodyStyle={{
          borderTopLeftRadius: "8px",
          borderTopRightRadius: "8px",
          minHeight: "40vh",
        }}
      >
        <div className="cateLists">
          <Card key={cateContent?.id}>
            <div className="cardLeft">
              <Image src={cateContent?.image} />
            </div>
            <div className="cardRight">
              <div className="priceText">
                <span>
                  {cateContent?.name ? cateContent?.name : "暂无详情"}
                </span>
                <span style={{ color: "red" }}>
                  {`￥${cateContent?.price}`}
                </span>
                <Stepper
                  defaultValue={1}
                  min={1}
                  digits={0}
                  className="count"
                  onChange={(value) => {
                    stepperClick(value);
                  }}
                />
              </div>
            </div>
          </Card>
        </div>
        <Button
          block
          color="danger"
          size="large"
          onClick={() => {
            buttonCart();
          }}
        >
          确定
        </Button>
      </Popup>
      {/* 立即购买 弹出层 */}
      <Popup
        visible={buy}
        onMaskClick={() => {
          setBuy(false);
        }}
        bodyStyle={{
          borderTopLeftRadius: "8px",
          borderTopRightRadius: "8px",
          minHeight: "40vh",
        }}
      >
        <div className="cateLists">
          <Card key={cateContent?.id}>
            <div className="cardLeft">
              <Image src={cateContent?.image} />
            </div>
            <div className="cardRight">
              <div className="priceText">
                <span>
                  {cateContent?.name ? cateContent?.name : "暂无详情"}
                </span>
                <span style={{ color: "red" }}>
                  {`￥${cateContent?.price}`}
                </span>
                <Stepper
                  defaultValue={1}
                  min={1}
                  digits={0}
                  className="count"
                  onChange={(value) => {
                    stepperClick(value);
                  }}
                />
                <Input ref={iphone} placeholder="联系手机号" />
              </div>
            </div>
          </Card>
        </div>
        <Button
          block
          color="danger"
          size="large"
          onClick={() => {
            addOrders();
          }}
        >
          确定
        </Button>
      </Popup>
      {/* 购买弹窗 */}
      <Popup
        visible={buyForm}
        onMaskClick={() => {
          setBuy(false);
        }}
        bodyStyle={{ height: "40vh" }}
      ></Popup>
      {/* 图片预览部分 */}
      <ImageViewer.Multi
        images={images}
        visible={imageShow}
        defaultIndex={0}
        onClose={() => {
          setImageShow(false);
        }}
      />
    </div>
  );
}
